import express from "express";
import cors from "cors";
import DB from "./database";
import { Routes } from "./interfaces/routes.interface";
import { NextFunction, Request, Response } from "express";
// 
import { expressjwt } from 'express-jwt';
interface error {
    name: string;
}

console.log('app.app')
const secretKey = "kkk *_*"
const coursOptions = {
	methods: ["GET", "POST", "DELETE", "PUT"],
	optionsSuccessStatus: 200,
};
class App {
	app: express.Application; // 定义一个属性 app，类型为 express.Application
	port = 3000; // 定义一个属性 port，类型为 string 或 number
	constructor(routers: Routes[]) {
		// 定义一个构造函数，接收一个参数 routes，类型为 Routes[]
		this.app = express(); // 在构造函数中初始化 app 属性，调用 express() 方法创建一个 express 实例
		this.connectToDatabase(); // 在构造函数中调用 connectToDatabase 方法连接数据库
        this.initializeMiddlewares();
        this.initializeRoutes(routers);
	}

	// 定义一个方法 connectToDatabase，返回一个 Promise，类型为 void
	private  connectToDatabase() {
        DB.sequelize.sync({ force: false }); // 调用 DB.authenticate() 方法连接数据库
        console.log("数据库连接成功"); // 输出连接成功的信息	
	}

    /**
     * 初始化中间件
     */
	private initializeMiddlewares() {
		this.app.use(cors(coursOptions));
		this.app.use(express.json());
		this.app.use(express.urlencoded({ extended: true }) );	
        this.app.use(
            expressjwt({
                secret: secretKey,
                algorithms: ['HS256']
            }).unless({path: [/^\/app\//]})
        )
        this.app.use((err: error, req: Request, res: any, next: NextFunction) => {
            console.log("触发了拦截器")
            //token解析失败导致的错误
            if (err.name === 'UnauthorizedError') {
                return res.send({status: 401, message: '无效的token'})
            }
            //其它原因导致的错误
            res.send({status: 500, message: '未知错误'})
        });
	}

    private initializeRoutes(routes: Routes[]) {
        routes.forEach(route => {
            this.app.use('/app', route.router);
        });	
    }
    public listen() {
        this.app.listen(this.port, () => {
            console.log(`App listening on the port http://localhost:${this.port}`);
        });
    }
}
export default App;